package com.weai.portal.service.impl;

import com.google.gson.Gson;
import com.weai.entity.Task;
import com.weai.portal.entity.AiList;
import com.weai.portal.entity.TaskReport;
import com.weai.portal.repository.AiListRepository;
import com.weai.portal.repository.TaskReportRepository;
import com.weai.portal.service.AiListService;
import com.weai.portal.service.TaskReportAIService;
import com.weai.portal.service.TaskReportService;
import com.weai.service.TaskService;
import com.weai.util.DateUtils;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * AI清单服务实现类
 */
@Service
@Slf4j
public class TaskReportServiceImpl implements TaskReportService {

    @Autowired
    private TaskReportRepository taskReportRepository;

    @Autowired
    private TaskService taskService;

    @Autowired
    private TaskReportAIService taskReportAIService;
    
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private static final DateTimeFormatter FILE_DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd");
    
    // 定义Windows和Linux系统的保存路径
    private static final String WIN_PATH = "C:\\Users\\Administrator\\Documents\\reports";
    private static final String LINUX_PATH = "/data/app/deposit_system/reports";

    @Override
    public List<TaskReport> getAllAiReports() {
        // 获取本周的日期范围
        Map<String, LocalDate> dateRange = DateUtils.getCurrentAndLastWeekDateRange();
        LocalDate startOfWeek = dateRange.get("startOfWeek");
        LocalDate endOfWeek = dateRange.get("endOfWeek");
        return taskReportRepository.findAll(startOfWeek, endOfWeek);
    }

    @Override
    @Transactional
    public void genAllAiReports() {
        List<TaskReport> taskReportList =new ArrayList<>();
        
        // 获取当前和上周的日期范围
        Map<String, LocalDate> dateRange = DateUtils.getCurrentAndLastWeekDateRange();
        LocalDate startOfWeek = dateRange.get("startOfWeek");
        LocalDate endOfWeek = dateRange.get("endOfWeek");
        LocalDate startOfLastWeek = dateRange.get("startOfLastWeek");
        LocalDate endOfLastWeek = dateRange.get("endOfLastWeek");
        
        // 查询本周任务
        List<Task> lastTasks = taskService.findByDate(startOfLastWeek, endOfLastWeek);
        log.info("AI周报生成，获取上周任务数量: {}", lastTasks.size());
        // 查询上周任务
        List<Task> currentTasks = taskService.findByDate(startOfWeek, endOfWeek);
        log.info("AI周报生成，获取本周任务数量: {}", currentTasks.size());
        // 生成AI周报
        for (Task curTask : currentTasks) {
            TaskReport taskReport = new TaskReport();
            taskReport.setTitle(curTask.getTitle());
            taskReport.setStatus(curTask.getStatus());
            // 设置需求类型和子类型（根据业务规则设置）
//            setTaskTypeAndSubType(taskReport, curTask);
            taskReport.setType(curTask.getType());
            taskReport.setSubType(curTask.getSubType());
            taskReport.setPeriodStartDate(startOfWeek);
            taskReport.setPeriodEndDate(endOfWeek);
            taskReport.setActualProgress(curTask.getThisWeekPlan());
            taskReport.setProblems(curTask.getProblems());
            taskReport.setReceiver(curTask.getReceiver());
            taskReport.setBusiDepartment(curTask.getBusiDepartment());
            taskReport.setBusiGoal(curTask.getBusiGoal());
            taskReport.setItDepartment(curTask.getItDepartment());
            for (Task lastTask : lastTasks) {
                if (curTask.getTitle().equals(lastTask.getTitle())) {
                    taskReport.setOriginalPlan(lastTask.getNextWeekPlan());
                    if ((curTask.getStatus().equals("todo") && lastTask.getStatus().equals("todo")) || (curTask.getStatus().equals("inProgress") && lastTask.getStatus().equals("todo"))) {
                        taskReport.setIsNewProject("是");
                    } else {
                        taskReport.setIsNewProject("否");
                    }
                    if ((curTask.getStatus().equals("done") && lastTask.getStatus().equals("todo")) || (curTask.getStatus().equals("done") && lastTask.getStatus().equals("inProgress"))) {
                        taskReport.setIsNewDone("是");
                    } else {
                        taskReport.setIsNewDone("否");
                    }
                }


            }
            taskReportList.add(taskReport);
        }
        log.info("完成AI周报数据准备！总共 {} 条！", taskReportList.size());
        int num = 1;
        for (TaskReport taskReport : taskReportList) {
            log.info("AI 开始 分析任务 {}/{} : \n {} \n", num,taskReportList.size(),taskReport);
            // 调用AI接口分析任务
            String result = taskReportAIService.analyzeTask(taskReport);
            Gson gson = new Gson();
            Map<String, Object> mapResult = gson.fromJson(result, Map.class);
//            taskReport.setIsNewProject((String) mapResult.get("isNewProject"));
            taskReport.setProgressRating((String) mapResult.get("progressRating"));
            taskReport.setProgressSummary((String) mapResult.get("progressSummary"));
            log.info("AI 完成 分析任务  {}/{} : \n {} \n", num,taskReportList.size(), taskReport);
            num++;
        }
        // 删除现有的AI周报数据
        taskReportRepository.deleteByDate(startOfWeek, endOfWeek);
        log.info("删除本周已生成的周报数据完成！");
        // 插入数据
        taskReportRepository.saveAll(taskReportList);
        log.info("插入本周报数据完成！");
    }
    
    /**
     * 根据业务规则设置任务类型和子类型
     * @param taskReport 任务报告
     * @param task 原始任务
     */
    private void setTaskTypeAndSubType(TaskReport taskReport, Task task) {
        // 示例逻辑，根据实际业务规则进行调整
        String taskType = task.getType();
        if (taskType == null || taskType.isEmpty()) {
            // 默认设置
            taskReport.setType("业务需求");
            taskReport.setSubType("业务自驱型");
        } else if (taskType.contains("科技") || taskType.contains("技术")) {
            taskReport.setType("科技专项");
            if (taskType.contains("个人")) {
                taskReport.setSubType("个人效能提升");
            } else if (taskType.contains("工具")) {
                taskReport.setSubType("公共工具建设");
            } else {
                taskReport.setSubType("数字员工建设");
            }
        } else {
            taskReport.setType("业务需求");
            if (taskType.contains("平台") || taskType.contains("赋能")) {
                taskReport.setSubType("平台赋能型");
            } else if (taskType.contains("联合") || taskType.contains("攻坚")) {
                taskReport.setSubType("联合攻坚型");
            } else {
                taskReport.setSubType("业务自驱型");
            }
        }
    }
    
    @Override
    public void exportToExcel(HttpServletResponse response) {
        try {
            List<TaskReport> taskReports = getAllAiReports();
            
            // 创建工作簿和工作表
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("任务报告");
            
            // 创建标题样式
            CellStyle headerStyle = workbook.createCellStyle();
            Font headerFont = workbook.createFont();
            headerFont.setBold(true);
            headerStyle.setFont(headerFont);
            
            // 创建表头
            Row headerRow = sheet.createRow(0);
            String[] headers = {
                "ID", "任务标题", "新接受的任务", "新完成的任务", "状态", "需求类型", "需求子类型","业务部门","业务目标",
                "任务进展AI评价", "任务AI总结", "周期开始日期", "周期结束日期",
                "预计进展", "实际进展", "存在的问题", "任务处理人", "创建时间"
            };
            
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
                cell.setCellStyle(headerStyle);
                sheet.setColumnWidth(i, 256 * 20); // 设置列宽
            }
            
            // 填充数据
            int rowNum = 1;
            for (TaskReport report : taskReports) {
                Row row = sheet.createRow(rowNum++);
                row.createCell(0).setCellValue(report.getId() != null ? report.getId().toString() : "");
                row.createCell(1).setCellValue(report.getTitle() != null ? report.getTitle() : "");
                row.createCell(2).setCellValue(report.getIsNewProject() != null ? report.getIsNewProject() : "");
                row.createCell(3).setCellValue(report.getIsNewDone() != null ? report.getIsNewDone() : "");
                row.createCell(4).setCellValue(report.getStatus() != null ? report.getStatus() : "");
                row.createCell(5).setCellValue(report.getType() != null ? report.getType() : "");
                row.createCell(6).setCellValue(report.getSubType() != null ? report.getSubType() : "");
                row.createCell(7).setCellValue(report.getBusiDepartment() != null ? report.getBusiDepartment() : "");
                row.createCell(8).setCellValue(report.getBusiGoal() != null ? report.getBusiGoal() : "");
                row.createCell(9).setCellValue(report.getProgressRating() != null ? report.getProgressRating() : "");
                row.createCell(10).setCellValue(report.getProgressSummary() != null ? report.getProgressSummary() : "");
                row.createCell(11).setCellValue(report.getPeriodStartDate() != null ? report.getPeriodStartDate().format(DATE_FORMATTER) : "");
                row.createCell(12).setCellValue(report.getPeriodEndDate() != null ? report.getPeriodEndDate().format(DATE_FORMATTER) : "");
                row.createCell(13).setCellValue(report.getOriginalPlan() != null ? report.getOriginalPlan() : "");
                row.createCell(14).setCellValue(report.getActualProgress() != null ? report.getActualProgress() : "");
                row.createCell(15).setCellValue(report.getProblems() != null ? report.getProblems() : "");
                row.createCell(16).setCellValue(report.getReceiver() != null ? report.getReceiver() : "");
                row.createCell(17).setCellValue(report.getCreatedTime() != null ? report.getCreatedTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) : "");
            }
            
            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment; filename=task_reports.xlsx");
            
            // 写入响应
            workbook.write(response.getOutputStream());
            workbook.close();
            
            log.info("成功导出{}条任务报告数据到Excel", taskReports.size());
        } catch (IOException e) {
            log.error("导出Excel失败", e);
            throw new RuntimeException("导出Excel失败: " + e.getMessage());
        }
    }
    
    @Override
    public String generateWeeklyHtml() {
        // 获取当前周期的报告数据
        List<TaskReport> taskReports = getAllAiReports();
        if (taskReports.isEmpty()) {
            return "<p>当前周期没有任务报告数据</p>";
        }

        try {
            // 调用大模型生成HTML
            return taskReportAIService.generateWeeklyReportHtml(taskReports);
        } catch (Exception e) {
            log.error("调用大模型生成HTML失败", e);
            // 如果大模型调用失败，回退到默认的HTML生成方法
            return generateDefaultHtml(taskReports);
        }
    }
    
    /**
     * 生成默认HTML（不使用大模型）
     * @param taskReports 任务报告列表
     * @return HTML内容
     */
    private String generateDefaultHtml(List<TaskReport> taskReports) {
        // 获取当前周期日期范围
        LocalDate periodStartDate = taskReports.get(0).getPeriodStartDate();
        LocalDate periodEndDate = taskReports.get(0).getPeriodEndDate();
        String dateRange = "";
        if (periodStartDate != null && periodEndDate != null) {
            dateRange = periodStartDate.format(DATE_FORMATTER) + " 至 " + periodEndDate.format(DATE_FORMATTER);
        }
        
        StringBuilder html = new StringBuilder();
        html.append("<!DOCTYPE html>")
            .append("<html lang=\"zh-CN\">")
            .append("<head>")
            .append("<meta charset=\"UTF-8\">")
            .append("<title>周报</title>")
            .append("<style>")
            .append("body { font-family: Arial, sans-serif; margin: 0; padding: 20px; }")
            .append("h1, h2 { color: #333; }")
            .append("table { border-collapse: collapse; width: 100%; margin-top: 20px; }")
            .append("th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }")
            .append("th { background-color: #f2f2f2; }")
            .append("tr:nth-child(even) { background-color: #f9f9f9; }")
            .append(".summary { margin-top: 30px; padding: 15px; background-color: #f8f8f8; border-radius: 5px; }")
            .append("</style>")
            .append("</head>")
            .append("<body>")
            .append("<h1>周报（").append(dateRange).append("）</h1>");
        
        // 添加摘要信息
        html.append("<div class=\"summary\">")
            .append("<h2>周报摘要</h2>")
            .append("<p>总任务数: ").append(taskReports.size()).append("</p>");
        
        // 统计各种状态的任务数量
        long todoCount = taskReports.stream().filter(r -> "todo".equals(r.getStatus())).count();
        long inProgressCount = taskReports.stream().filter(r -> "inProgress".equals(r.getStatus())).count();
        long doneCount = taskReports.stream().filter(r -> "done".equals(r.getStatus())).count();
        
        html.append("<p>待办任务: ").append(todoCount).append("</p>")
            .append("<p>进行中任务: ").append(inProgressCount).append("</p>")
            .append("<p>已完成任务: ").append(doneCount).append("</p>")
            .append("</div>");
        
        // 添加任务表格
        html.append("<table>")
            .append("<tr>")
            .append("<th>任务标题</th>")
            .append("<th>状态</th>")
            .append("<th>需求类型</th>")
            .append("<th>需求子类型</th>")
            .append("<th>预计进展</th>")
            .append("<th>实际进展</th>")
            .append("<th>存在问题</th>")
            .append("<th>进展评价</th>")
            .append("<th>总结</th>")
            .append("</tr>");
        
        // 添加任务数据行
        for (TaskReport report : taskReports) {
            String status = report.getStatus();
            if (status == null) status = "";
            
            // 将状态值映射为中文描述
            String statusText = switch (status) {
                case "todo" -> "待办";
                case "inProgress" -> "进行中";
                case "done" -> "已完成";
                default -> status;
            };
            
            html.append("<tr>")
                .append("<td>").append(report.getTitle() != null ? report.getTitle() : "").append("</td>")
                .append("<td>").append(statusText).append("</td>")
                .append("<td>").append(report.getType() != null ? report.getType() : "").append("</td>")
                .append("<td>").append(report.getSubType() != null ? report.getSubType() : "").append("</td>")
                .append("<td>").append(report.getOriginalPlan() != null ? report.getOriginalPlan() : "").append("</td>")
                .append("<td>").append(report.getActualProgress() != null ? report.getActualProgress() : "").append("</td>")
                .append("<td>").append(report.getProblems() != null ? report.getProblems() : "").append("</td>")
                .append("<td>").append(report.getProgressRating() != null ? report.getProgressRating() : "").append("</td>")
                .append("<td>").append(report.getProgressSummary() != null ? report.getProgressSummary() : "").append("</td>")
                .append("</tr>");
        }
        
        html.append("</table>");
        html.append("</body></html>");
        
        return html.toString();
    }

    @Override
    public String saveHtmlToServer(String htmlContent) {
        // 检查内容是否为空
        if (htmlContent == null || htmlContent.isEmpty()) {
            throw new IllegalArgumentException("HTML内容不能为空");
        }
        
        try {
            // 确定操作系统类型并设置保存路径
            String osName = System.getProperty("os.name").toLowerCase();
            String basePath = osName.contains("win") ? WIN_PATH : LINUX_PATH;
            
            // 创建目录（如果不存在）
            Path dirPath = Paths.get(basePath);
            if (!Files.exists(dirPath)) {
                Files.createDirectories(dirPath);
                log.info("创建目录: {}", dirPath);
            }
            
            // 生成文件名：AI虚拟架构组周报_当前日期八位.html
            String fileName = String.format("AI虚拟架构组周报_%s.html", 
                                           LocalDate.now().format(FILE_DATE_FORMATTER));
            Path filePath = dirPath.resolve(fileName);
            
            // 写入文件
            Files.write(filePath, htmlContent.getBytes(StandardCharsets.UTF_8));
            log.info("成功保存HTML到: {}", filePath);
            
            return filePath.toString();
        } catch (IOException e) {
            log.error("保存HTML文件失败", e);
            throw new RuntimeException("保存HTML文件失败: " + e.getMessage(), e);
        }
    }

    @Override
    @Transactional
    public TaskReport updateTaskReport(Integer id, TaskReport taskReport) {
        log.info("开始更新任务报告，ID: {}", id);
        
        // 查找现有的任务报告
        TaskReport existingReport = taskReportRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("任务报告不存在，ID: " + id));
        
        // 更新字段（只更新非空字段）
        if (taskReport.getTitle() != null) {
            existingReport.setTitle(taskReport.getTitle());
        }
        if (taskReport.getReceiver() != null) {
            existingReport.setReceiver(taskReport.getReceiver());
        }
        if (taskReport.getStatus() != null) {
            existingReport.setStatus(taskReport.getStatus());
        }
        if (taskReport.getType() != null) {
            existingReport.setType(taskReport.getType());
        }
        if (taskReport.getSubType() != null) {
            existingReport.setSubType(taskReport.getSubType());
        }
        if (taskReport.getBusiDepartment() != null) {
            existingReport.setBusiDepartment(taskReport.getBusiDepartment());
        }
        if (taskReport.getBusiGoal() != null) {
            existingReport.setBusiGoal(taskReport.getBusiGoal());
        }
        if (taskReport.getItDepartment() != null) {
            existingReport.setItDepartment(taskReport.getItDepartment());
        }
        if (taskReport.getOriginalPlan() != null) {
            existingReport.setOriginalPlan(taskReport.getOriginalPlan());
        }
        if (taskReport.getActualProgress() != null) {
            existingReport.setActualProgress(taskReport.getActualProgress());
        }
        if (taskReport.getProblems() != null) {
            existingReport.setProblems(taskReport.getProblems());
        }
        if (taskReport.getProgressRating() != null) {
            existingReport.setProgressRating(taskReport.getProgressRating());
        }
        if (taskReport.getProgressSummary() != null) {
            existingReport.setProgressSummary(taskReport.getProgressSummary());
        }
        if (taskReport.getPeriodEndDate() != null) {
            existingReport.setPeriodEndDate(taskReport.getPeriodEndDate());
        }
        
        // 保存更新后的任务报告
        TaskReport updatedReport = taskReportRepository.save(existingReport);
        log.info("成功更新任务报告，ID: {}", id);
        
        return updatedReport;
    }
}